package com.bocloud.cmp.driver.convertor.os;

import java.util.List;
import java.util.Set;

import org.openstack4j.model.network.IP;
import org.openstack4j.model.network.Port;

import com.bocloud.cmp.driver.convertor.BeanConvert;
import com.bocloud.cmp.model.PortModel;
import com.google.common.collect.Lists;

public class ConverPort implements BeanConvert<PortModel, Port> {

	@Override
	public List<PortModel> convertList(List<? extends Port> models) {
		List<PortModel> portModels = Lists.newArrayList();
		for (Port port : models) {
			portModels.add(convertModel(port));
		}
		return portModels;
	}

	@Override
	public PortModel convertModel(Port port) {
		String name = port.getName();
		String portId = port.getId();
		// 如果name，取ID的前12位
		if (name.equals("")) {
			name = portId.substring(0, 13);
		}
		Set<? extends IP> fixedIps = port.getFixedIps();
		String ipAddress = "";
		String subnetId = "";
		// 如果有多个用逗号隔开
		for (IP fixedIp : fixedIps) {
			ipAddress += fixedIp.getIpAddress() + ",";
			subnetId += fixedIp.getSubnetId() + ",";
		}
		if (!ipAddress.isEmpty()) {
			ipAddress = ipAddress.substring(0, ipAddress.length() - 1);
		}
		if (!subnetId.isEmpty()) {
			subnetId = subnetId.substring(0, subnetId.length() - 1);
		}
		PortModel portModel = new PortModel(name, port.getState().toString(), port.getDeviceId(), port.getDeviceOwner(),
				ipAddress, subnetId, port.getNetworkId(), port.getMacAddress(), portId);

		return portModel;
	}

}
